//
//  QRCodeViewController.swift
//  CXSwiftWB
//
//  Created by meidaeriOS on 2017/5/23.
//  Copyright © 2017年 meidaer. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {

    @IBOutlet weak var customContainView: UIView!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    
    @IBOutlet weak var scanImageView: UIImageView!
    
    @IBOutlet weak var tabbarCustom: UITabBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        // 设置默认选中 
        tabbarCustom.selectedItem = tabbarCustom.items?.first
        tabbarCustom.delegate = self
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
    }
    
    /// 开启冲击波动画 
    fileprivate func startAnimation()
    {
        topConstraint.constant = -heightConstraint.constant
        view.layoutIfNeeded()
        UIView.animate(withDuration: 2.0) { 
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.topConstraint.constant = self.heightConstraint.constant
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 内部控制的方法
    fileprivate func  scanQRCode()
    {
        if !session.canAddInput(input) {
            return
        }
        if !session.canAddOutput(output) {
            return
        }
        // 3.添加输入和输出到会话中
        session.addInput(input)
        session.addOutput(output)
        
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        
        // 设置监听输出解析到的数据
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        
        // 添加预览图层
        view.layer.insertSublayer(preViewLayer, at: 0)
        preViewLayer.frame = view.bounds
        
        // 添加容器图层
        view.layer.addSublayer(containerLayer)
        containerLayer.frame = view.bounds
        
        // 开始扫描
        session.startRunning()
    }
    
    @IBAction func rightItemClick(_ sender: Any) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            return
        }
        
        // 创建相册控制器
        let imagePickerVC = UIImagePickerController()
        imagePickerVC.delegate = self
        present(imagePickerVC, animated: true, completion: nil)
        
    }
    
    @IBAction func letfItemtClick(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: - 懒加载
    
    // 输入对象
    fileprivate lazy var input: AVCaptureDeviceInput = {
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        let input = try! AVCaptureDeviceInput(device: device)
        return input
    }()
    
    /// 会话
    fileprivate lazy var session: AVCaptureSession = AVCaptureSession()
    
    /// 输出对象
    fileprivate lazy var output: AVCaptureMetadataOutput = {
        let out = AVCaptureMetadataOutput()
        
        // 获取屏幕的frame 
        let viewRect = self.view.frame
        // 获取 扫描容器的frame, 是以它的横轴来的
        let containerRect = self.customContainView.frame
        let x = containerRect.origin.y / viewRect.height
        let y = containerRect.origin.x / viewRect.width
        let width = containerRect.height / viewRect.height
        let height = containerRect.width / viewRect.width
        
        // 设置输出对象的范围
        out.rectOfInterest = CGRect(x: x, y: y, width: width, height: height)
        return out
    }()
    
    /// 预览图层
    fileprivate lazy var preViewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    
    /// 专门用于保存描边的图层
    fileprivate lazy var containerLayer: CALayer = CALayer()
    
}

extension QRCodeViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // 去除选中的图片
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            return
        }
        
        guard let ciImage = CIImage(image: image) else {
            return
        }
        
        // 2.从选中的图片中读取二维码数据
        let  detecor = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyLow])
        // 2.2 利用探测器探测数据
        let results = detecor?.features(in: ciImage)
        
        // 取出探测器中的数据
        for result in results! {
            CXLog((result as! CIQRCodeFeature).messageString)
        }
    }
}

extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        
    }
    
    /// 绘制描边
    fileprivate func drawLines(_ objc: AVMetadataMachineReadableCodeObject) {
        // 0.安全校验
        guard let array = objc.corners else {
            return
        }
        
        // 创建图层
        let layer = CAShapeLayer()
        layer.lineWidth = 2
        layer.strokeColor = UIColor.green.cgColor
        layer.fillColor = UIColor.clear.cgColor
        
        // 2.创建UIBezierPath
        let path = UIBezierPath()
        var point = CGPoint.zero
        var index = 0
        point = CGPoint(dictionaryRepresentation: array[index] as! CFDictionary)!
        // 将起点移动到某一个点
        path.move(to: point)
        
        // 2.2连接其它线段
        
    }
}

extension QRCodeViewController: UITabBarDelegate {
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        heightConstraint.constant = (item.tag == 1) ? 250 : 150
        view.layoutIfNeeded()
        // 移除动画
        scanImageView.layer.removeAllAnimations()
        
        // 重新开启动画
        startAnimation()
    }
}
